<?php

namespace addons\TfFutures\backend\controllers;

use addons\TfFutures\common\models\Lever;
use addons\TfFutures\common\models\SymbolCate;
use yii;
use common\components\Curd;
use yii\data\Pagination;

class LeverController extends BaseController
{
    use Curd;
    public $modelClass = Lever::class;

    public function actionIndex()
    {
        $search = Yii::$app->request->get('keyword','');
        $data   = $this->modelClass::find();
        if (!empty($search)) {
            $data->andFilterWhere(['like','name',$search]);
        }
        $pages  = new Pagination(['totalCount' => $data->count(), 'pageSize' => $this->pageSize]);
        $models = $data->offset($pages->offset)
                       ->orderBy('id desc')
                       ->limit($pages->limit)
                       ->all();

        return $this->render($this->action->id, [
            'models' => $models,
            'pages'  => $pages,
            'keyword'=> $search,
        ]);
    }

    /**
     * 返回模型
     *
     * @param $id
     * @return \yii\db\ActiveRecord
     */
    protected function findModel($id)
    {
        /* @var $model \yii\db\ActiveRecord */
        if (empty($id) || empty(($model = $this->modelClass::find()->where(['id' => $id])->one()))) {
            $model = new $this->modelClass;
            return $model->loadDefaultValues();
        }

        return $model;
    }

    /**
     * @return mixed|string|\yii\console\Response|\yii\web\Response
     * @throws \yii\base\ExitException
     */
    public function actionAjaxEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id');
        $model = $this->findModel($id);
        // ajax 验证
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }

        return $this->renderAjax($this->action->id, [
            'model' => $model,
        ]);
    }
    public function actionEdit($id)
    {
        $model = $this->modelClass::findOne($id);
        $cateDropDownList = SymbolCate::getEditDropDownList($id);unset($cateDropDownList[0]);
        return $this->render($this->action->id, [
            'model' => $model,
            'cateDropDownList' => $cateDropDownList,
        ]);
    }

    /**
     * 删除
     *
     * @param $id
     * @return mixed
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionDelete($id)
    {
        if ($this->modelClass::findOne($id)->delete()) {
            return $this->message("删除成功", $this->redirect(['index']));
        }

        return $this->message("删除失败", $this->redirect(['index']), 'error');
    }

}